package com.huyandroid.AccountMonitor1;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TabHost.TabSpec;

public class MainActivity extends Activity implements OnClickListener,OnItemClickListener, OnTabChangeListener {
	///For Flipping Action///////////
	private ViewFlipper mainFlipper,childFlipper;
	private int currentScreen;
	////For LOGIN
	private EditText  user, pass;
	
	////For Admin's Managering
	private ListView lv,lv2;//can we use only one to find ID beside Oncreate?
	private UsersHandler userDB;
	private TabHost th;
	
	////For User Tab1
	private EditText _name,_email, _phone, _account;
	private int memberID;
	////For Tab2
	private TextView _accountNo;
	private TextView _balance;
	private EditText _search;
	private Spinner sp1;
	private String _tagID;
	
	private ExchangeHandler exDB;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);// no title application
        setContentView(R.layout.mainflipping);
        
        mainFlipper=(ViewFlipper)findViewById(R.id.MainFlipper);
        childFlipper=(ViewFlipper)findViewById(R.id.ChildFlipper);
        // Activate Button, TextView,...
        Button btntemp=(Button)findViewById(R.id.btnLogin);
        btntemp.setOnClickListener(this);
        btntemp=(Button)findViewById(R.id.btnRegister);
        btntemp.setOnClickListener(this);
        
        
        TextView tv=(TextView)findViewById(R.id.link_to_register);
        tv.setOnClickListener(this);
        
        user=(EditText)findViewById(R.id.userName);
        pass=(EditText)findViewById(R.id.password);
        
        //Tab host
        th=(TabHost)findViewById(R.id.tabhost);
        th.setOnTabChangedListener(this);
        th.setup();
        TabSpec specs=th.newTabSpec("tag1");
        specs.setContent(R.id.tab1);
        specs.setIndicator("About",getResources().getDrawable(R.drawable.ic_launcher));
        th.addTab(specs);
        specs=th.newTabSpec("tag2");
        specs.setContent(R.id.tab2);
        specs.setIndicator("History",getResources().getDrawable(R.drawable.ic_launcher));
        th.addTab(specs);
        
        specs=th.newTabSpec("tag3");
        specs.setContent(R.id.tab3);
        specs.setIndicator("Route",getResources().getDrawable(R.drawable.ic_launcher));
        th.addTab(specs);
       
        
        
        //th.getTabWidget().setDividerDrawable(R.drawable.ic_launcher);
        
        //setupTab(new TextView(this), "About",R.id.tab1);
    	//setupTab(new TextView(this), "History",R.id.tab2);
    	//setupTab(new TextView(this), "Route",R.id.tab3);
        
        ////////////FOR ADMIN CONTROL DATA///////////////////////////
        btntemp=(Button)findViewById(R.id.btnShowUsers);
        btntemp.setOnClickListener(this);
        btntemp=(Button)findViewById(R.id.btnAdminBack);
        btntemp.setOnClickListener(this);
        lv=(ListView)findViewById(R.id.lvAdmin);
        lv.setOnItemClickListener(this);
       
        ///Activate the database of users
        userDB=new UsersHandler(this,"usersManager");  ////usersManager if it exist, if no then...??
        
        ///////FOR REGISTRATION OF NEW MEMBER/////////////////////////
        btntemp=(Button)findViewById(R.id.btnRegister);
        btntemp.setOnClickListener(this);
        tv=(TextView)findViewById(R.id.link_to_login);
        tv.setOnClickListener(this);
        ////////////FOR TAB 1 --USER////////////////////////////////////
        btntemp=(Button)findViewById(R.id.btnBack);
        btntemp.setOnClickListener(this);
        btntemp=(Button)findViewById(R.id.btnUpdate);
        btntemp.setOnClickListener(this);
        
        _name=(EditText)findViewById(R.id.txtFullName);
        _email=(EditText)findViewById(R.id.txtEmail);
        _phone=(EditText)findViewById(R.id.txtPhoneNumber);
        _account=(EditText)findViewById(R.id.txtAccount);
        ///////////////FOR TAB 2--EXCHANGE/////////////////////////////////
        //If necessary????
        _accountNo=(TextView)findViewById(R.id.txtAccountNo);
        _balance=(TextView)findViewById(R.id.txtBalance);
        _search=(EditText)findViewById(R.id.etxSearch);
        lv2=(ListView)findViewById(R.id.lvExchange);
        lv2.setOnItemClickListener(this);
        //for spinner-search
        sp1=(Spinner)findViewById(R.id.spinner1);
        sp1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
        
        //for update screen
        btntemp=(Button)findViewById(R.id.btnBackExchange);
        btntemp.setOnClickListener(this);
        btntemp=(Button)findViewById(R.id.btnOkExchange);
        btntemp.setOnClickListener(this);
    }
  
	////////////////////////CUSTOMED TAB IN ANDROID////////////////////////////////////////
    public void setupTab(final View view, final String tag,int layout_Id) {
    	View tabview = createTabView(th.getContext(), tag);
            TabSpec setContent = th.newTabSpec(tag).setIndicator(tabview).setContent(layout_Id);
    	th.addTab(setContent);
    }
    
    private static View createTabView(final Context context, final String text) {
    	View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
    	TextView tv = (TextView) view.findViewById(R.id.tabsText);
    	tv.setText(text);
    	return view;
    }
    /////////////////////////////////////////////////////////////////////////////////
    
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		
	}
	public void onTabChanged(String tagID) {
		// TODO Auto-generated method stub
		_tagID=tagID;
		//if(tagID.equals("tag2"))showscreen(childFlipper,1,true);
	}
 

	public void onClick(View v) {
		// TODO Auto-generated method stub
		int viewID = v.getId();
		switch (viewID) {
		case R.id.btnLogin: login();
			break;
		case R.id.link_to_register: showscreen(mainFlipper,2,true);
			break;
		case R.id.btnBack: showscreen(mainFlipper,0,true);
			break;
		case R.id.btnRegister:register();
			break;
		case R.id.link_to_login: showscreen(mainFlipper,0,true);
			break;
		case R.id.btnAdminBack:showscreen(mainFlipper,0,true);
			break;
		case R.id.btnUpdate: if(_tagID.equals("tag2")){
								//mainFlipper.invalidate();
								showscreen(childFlipper,1,true);
								
								}
							else updateUser();
			break;
		case R.id.btnBackExchange: showscreen(childFlipper,0,true); LoadExchangeData(memberID);
			break;
		case R.id.btnOkExchange : updateExchange();
		}
	}
	
	public void updateUser(){
		if(memberID==-1)return;
		userDB.open();
		String N=_name.getText().toString();
		String E=_email.getText().toString();
		String P=_phone.getText().toString();
		String A=_account.getText().toString();
		boolean sign=userDB.updateItem(memberID, N, E, P, A);
		userDB.close();
		if(sign) Toast.makeText(getBaseContext(), "Update Sucessfully", Toast.LENGTH_LONG).show();
		
	}
	public void updateExchange(){ // insert !!!
		String E,B,D,T,Pr,Dt,Pt;
		EditText temp=(EditText)findViewById(R.id.etxExchange);
		E=temp.getText().toString();
		temp=(EditText)findViewById(R.id.etxBalance);
		B=temp.getText().toString();
		temp=(EditText)findViewById(R.id.etxDate);
		D=temp.getText().toString();
		temp=(EditText)findViewById(R.id.etxTime);
		T=temp.getText().toString();
		temp=(EditText)findViewById(R.id.etxProvince);
		Pr=temp.getText().toString();
		temp=(EditText)findViewById(R.id.etxDistrict);
		Dt=temp.getText().toString();
		temp=(EditText)findViewById(R.id.etxPoint);
		Pt=temp.getText().toString();
		exDB.open();
		//boolean sign =exDB.updateItem(memberID, E, B,T +"-"+ D , Pr +"-"+Dt+"-"+Pt);
		Exchange exchange=new Exchange(E, B,T +"-"+ D , Pr +"-"+Dt+"-"+Pt);
		exDB.addItem(exchange);
		exDB.close();
		//if(sign) Toast.makeText(getBaseContext(), "Update Sucessfully", Toast.LENGTH_LONG).show();
		
	}
	public void register(){
		EditText regName=(EditText)findViewById(R.id.reg_name);
		EditText regPass=(EditText)findViewById(R.id.reg_password);
		String N=regName.getText().toString();
		String P=regPass.getText().toString();
		userDB.open();
		userDB.addItem(new User(N,P));  ///HOW TO SET ID of the new user???
		userDB.close();
		
		Toast.makeText(getBaseContext(), "Added Sucessfully", Toast.LENGTH_LONG).show();
	}
	
	
	public void login(){
		
		String Uname=user.getText().toString();
		String Upass=pass.getText().toString();
		if(Uname.equals("admin")&& Upass.equals("admin"))login4Admin();
		else {
			
		
			  memberID= checkUser(Uname,Upass);
			  if(memberID==-1) Toast.makeText(getBaseContext(), "You enter wrong username or password "+ memberID, Toast.LENGTH_LONG).show();
			  else {
				     showscreen(mainFlipper,1,true);
				     ///Update data on Tab 1
				    LoadExchangeData(memberID);
			  }
		}
	}
	public void LoadExchangeData(int memID){
		  userDB.open();
		  	 String[] row=userDB.getAllfromItem(memID);
		     userDB.close();
		     Toast.makeText(getBaseContext(), "ID:= "+ memID , Toast.LENGTH_LONG).show();
		  	 ////For TAB 1
		  		_name.setText(row[3]);
		  		_email.setText(row[4]);
		  		_phone.setText(row[5]);
		  		_account.setText(row[6]);
		  		
		  	/////For TAB 2
		  		_accountNo.setText(row[6]);
		  		_balance.setText("$1000.000");
		  	////upload exchange data to Tab2
		  		exDB=new ExchangeHandler(this,"exchangeManager"+memID);
		  		
		  		if(exDB.databaseExist())
		  		{
		  			exDB.open();
		  			List<Exchange> L=exDB.getAllItems();
		  			exDB.close();
		  			int N=L.size();
		  			String[] data=new String[N];
		  			int i=N-1;
	
		  			for(Exchange ex : L){
		  				String temp=ex.getExchange() + " - "+ex.getBalance()+" - "+ex.getTime()+" - "+ex.getPlace();
		  				data[i]=temp;
		  				i--; // print to listview from newest -->oldest
		  			}
		  			lv2.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data));
		  			//update current balance
		  			_balance.setText(L.get(N-1).getBalance());
		  		}
		  		
	}
	public void login4Admin(){
		
		userDB.open();
		List<User> userList=userDB.getAllItems();
		userDB.close();
		int N=userList.size();
    	String[] data=new String[N];
    	int i=0;
		for (User ur : userList){
			String row="No: "+i+": "+ ur.getId()+" - "+ur.getUserName()+" - "+ur.getPassword();
			data[i]=row;
			i++;
		}
		lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data));
		showscreen(mainFlipper,3,true);
		Toast.makeText(getBaseContext(), "login as Admin Sucessfully", Toast.LENGTH_LONG).show();
	}
	private int checkUser(String name, String pwd){
		/// if member -->return ID of the user
		///if not member ---> return -1	
		int isMember=-1;
		userDB.open();
		///method 1: get all items -->then check if there is item =(name,pwd) -->very poor
		List<User> userList=userDB.getAllItems();
		userDB.close();
		for (User ur : userList){
			if((ur.getUserName().equals(name))&& (ur.getPassword().equals(pwd))) 
				{
					isMember= ur.getId();
					break;
				}
		}
		return isMember;
	}
	
	 ///-------------For Free Memory --are they important? if they dont be used?--
    @Override
   	protected void onStop() {
   		super.onStop();
   		
   	}
   	@Override
   	protected void onDestroy() {
   		super.onDestroy();
   		
   	}
   	@Override
   	protected void onResume() {
   		super.onResume();
   		
   	}
   	
  //********************************My class, method() Definition***********************************//
  //--------------------View Flip Animation------------------------------------------------------//	
  	 private void showscreen(ViewFlipper flippy,int newSlide, boolean n2c) {
  			//if (n2c && newSlide == currentScreen) return; 
  			//flippy.setInAnimation(inFromDownRightAnimation());
  		    //flippy.setOutAnimation(outToUpLeftAnimation());
  			flippy.setInAnimation(inFromRightAnimation());
  			flippy.setOutAnimation(outToLeftAnimation());
  		    flippy.setDisplayedChild(newSlide); 
  		    //currentScreen=newSlide;
  	 }
      //-------------------------Fade_In_Animation----------------------------------------------------//
  	 private Animation fade_in_Animation()
  	 {Animation in;
  	 in=AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
  	 in.setDuration(1000);
      	return in;
  		 
  	 }
  	 
  	 
  	//-------------------------Fade_Out_Animation---------------------------------------------------//
  	 private Animation fade_out_Animation()
  	 {Animation out;
  	 out=AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
  	 out.setDuration(1000);
  	 	return out;
  		 
  	 }
  	//-------------------------slide_Out_right Animation---------------------------------------------------//
  		 private Animation slide_out_right_Animation()
  		 {Animation out;
  		 out=AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
  		 out.setDuration(1000);
  		 	return out;
  			 
  		 }
  		//-------------------------slide_Out_right Animation---------------------------------------------------//
  		 private Animation slide_in_left_Animation()
  		 {Animation in;
  		 in=AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
  		 in.setDuration(1000);
  		 	return in;
  			 
  		 }
  	 
  	 
  	//-----------------------In from Right, Out from Left-------------------------------------//
  	 	   private Animation inFromRightAnimation() {
  				Animation inFromRight = new TranslateAnimation(
  						Animation.RELATIVE_TO_PARENT,  1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
  						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
  						);
  				inFromRight.setDuration(1000);
  				inFromRight.setInterpolator(new AccelerateInterpolator());
  				return inFromRight;
  			}

  			private Animation outToLeftAnimation() {
  				Animation outtoLeft = new TranslateAnimation(
  						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,
  						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
  						);
  				outtoLeft.setDuration(1000);
  				outtoLeft.setInterpolator(new AccelerateInterpolator());
  				return outtoLeft;
  			} 
  	        //----------------In form Left, Out from Right---------------------------------------------//
  			private Animation inFromLeftAnimation() {
  				Animation inFromRight = new TranslateAnimation(
  						Animation.RELATIVE_TO_PARENT,  -1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
  						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
  						);
  				inFromRight.setDuration(500);
  				inFromRight.setInterpolator(new AccelerateInterpolator());
  				return inFromRight;
  			}
  			private Animation outToRigthAnimation() {
  				Animation outtoLeft = new TranslateAnimation(
  						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  1.0f,
  						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
  						);
  				outtoLeft.setDuration(500);
  				outtoLeft.setInterpolator(new AccelerateInterpolator());
  				return outtoLeft;
  			} 
  	    
  	       //----------------------------------In from Up, out from down---------------------------//
  			private Animation inFromUpAnimation() {
  				Animation inFromRight = new TranslateAnimation(
  						///X coordinator
  						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
  						// Y coordinator
  						Animation.RELATIVE_TO_PARENT,  -1.0f, Animation.RELATIVE_TO_PARENT,   0.0f
  						);
  				inFromRight.setDuration(500);
  				inFromRight.setInterpolator(new AccelerateInterpolator());
  				return inFromRight;
  			}
  			private Animation outToDownAnimation() {
  				Animation outtoLeft = new TranslateAnimation(
  						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
  						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  1.0f
  						);
  				outtoLeft.setDuration(500);
  				outtoLeft.setInterpolator(new AccelerateInterpolator());
  				return outtoLeft;
  			} 
  	    
  	          //---In from Down, out from Up--------------------------------------------------------//
  				private Animation inFromDownAnimation() {
  					Animation inFromRight = new TranslateAnimation(
  							///X coordinator
  							Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
  							// Y coordinator
  							Animation.RELATIVE_TO_PARENT,  1.0f, Animation.RELATIVE_TO_PARENT,   0.0f
  							);
  					inFromRight.setDuration(500);
  					inFromRight.setInterpolator(new AccelerateInterpolator());
  					return inFromRight;
  				}
  				private Animation outToUpAnimation() {
  					Animation outtoLeft = new TranslateAnimation(
  							Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
  							Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   -1.0f
  							);
  					outtoLeft.setDuration(500);
  					outtoLeft.setInterpolator(new AccelerateInterpolator());
  					return outtoLeft;
  				} 
  		    
  	            //----In from Down Right; Out from Up Left----------------------------------------------//
  				private Animation inFromDownRightAnimation() {
  					Animation inFromRight = new TranslateAnimation(
  							///X coordinator
  							Animation.RELATIVE_TO_PARENT,  1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
  							// Y coordinator
  							Animation.RELATIVE_TO_PARENT,  1.0f, Animation.RELATIVE_TO_PARENT,   0.0f
  							);
  					inFromRight.setDuration(1000);
  					inFromRight.setInterpolator(new AccelerateInterpolator());
  					return inFromRight;
  				}
  				private Animation outToUpLeftAnimation() {
  					Animation outtoLeft = new TranslateAnimation(
  							Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,
  							Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   -1.0f
  							);
  					outtoLeft.setDuration(1000);
  					outtoLeft.setInterpolator(new AccelerateInterpolator());
  					return outtoLeft;
  				}
  				
    
}